import React, { Component, createRef } from 'react'

export default class TodoInput extends Component {
  // 创建 Ref 对象
  inputRef = createRef()

  // state
  state = {
    inputValue: ''
  }

  // 处理添加按钮点击动作
  handleAdd = event => {
    // 阻止默认
    event.preventDefault()
    // 添加
    this.props.onAdd(this.state.inputValue)
    // 清空文本框
    this.setState({
      inputValue: ''
    })
    // 文本框自动获得焦点
    // 字符串 ref 已废弃，不建议再使用
    // this.refs.inputRef.focus()
    // console.log(this.inputRef)
    this.inputRef.current.focus()
  }

  handleChange = event => {
    // console.log(event.target.value)
    this.setState({
      inputValue: event.target.value
    })
  }

  handleKeyDown = event => {
    if (event.keyCode === 13) {
      this.handleAdd(event)
    }
  }

  render() {
    return (
      <div className="field is-grouped container" style={ {marginTop: '12px'} }>
        <p className="control is-expanded">
          <input
            className="input"
            type="text"
            placeholder="请输入待办事项"
            value={this.state.inputValue}
            onChange={this.handleChange}
            ref={this.inputRef}
            onKeyDown={this.handleKeyDown}
          />
        </p>
        <p className="control">
          <a className="button is-primary" href="/" onClick={this.handleAdd}>
            添加
          </a>
        </p>
      </div>
    )
  }
}
